﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;


namespace Common
{
    public class treeSetView
    {
        public static void SetSelectTreeView(TreeView treeView,string nodeName)
        {
            treeView.Focus();
            //for(int i=0;i<treeView.Nodes.Count;i++)
            //{
            //    for (int j = 0; j < treeView.Nodes[i].Nodes.Count; j++)
            //    {
            //        if (treeView.Nodes[i].Text[j].ToString()==nodeName)
            //        {
            //            treeView.SelectedNode = treeView.Nodes[i].Nodes[j];
            //            treeView.Nodes[i].Expand();
            //            return;
            //        }
            //    }
            //}
            foreach (TreeNode node in treeView.Nodes)
            {
                if (FindNodeByName(treeView, node, nodeName))
                    return;
            }
        }
        private static bool FindNodeByName(TreeView treeView,TreeNode node,string nodeName)
        {
            if(node == null) 
                return false;
            if (node.Text == nodeName)
            {
                treeView.SelectedNode = node;
                ExpandNode(node); 
                return true;                
            } 
            foreach(TreeNode n in node.Nodes)
            {
                if (FindNodeByName(treeView, n, nodeName))
                    return true;
            }
            return false;
        }
        private static void ExpandNode(TreeNode node)
        {
            if (node.Level == 0)
            {
                node.Expand();
                return;
            }
            if (!string.IsNullOrEmpty(node.Parent.Text))
            {
                node.Parent.Expand();               
            }
            if (node.Parent.Level == 0)
            {
                node.Parent.Expand();
            }
            else
            {
                ExpandNode(node);
            }
        }
    }
}
